import json
from django.http import JsonResponse
from Web.WebClassCongregation import UserInfo,ActiveScanList
from Web.Workbench.Tasks import MedusaScan
from Web.Workbench.LogRelated import UserOperationLogRecord,RequestLogRecord
from ClassCongregation import ErrorLog


#接收数据样式
'''
{
	"url": "www.ascotbe.com",
	"token": "1EmWI2bgSWz477WQQMsgWidPSJmUiZy3B4VN0AYczjkdRs5fQvuhwOuek08bVSlzWV1HXf4fWupDgw8m9Lct4frZf5RqYPZBSvrXiIO3uvQ15FRNc8y5f1Rd8Y02CYQLF0BKW0S4qdmVo7k9yOGnpxHpGYfCYXfLi5ZRojsEHhevIEmeECSZL5awSXNWN9EyUQGjndoNoh5EZXxP4wstQA5JILjVldaqcfBElBgWJx4mKeZ9uFE9A4pI3i",
	"threads": 200,
	"module": "all",
	"header": "None",
	"proxy": "127.0.0.1:8080"
}
'''
##获取redis下发任务的Key，然后后台查询key来看是否工作完成，完成的话就查Medusa表然后写入ScanInformation表,到时候放到Tasks文件中
def Scan(request):
    RequestLogRecord(request, request_api="scan")
    if request.method == "POST":
        try:
            ReceiveData=json.loads(request.body)
            ScanUrl=ReceiveData["url"]
            ScanToken= ReceiveData["token"]
            ScanModule = ReceiveData["module"]
            ScanThreads = ReceiveData["threads"]
            ScanAgentHeader = ReceiveData["header"]
            ScanProxy = ReceiveData["proxy"]
            if ScanProxy==0:#如果传入0表示关闭该功能
                ScanProxy=None

            if type(ScanThreads)==int:#判断类型
                TokenQueryReturnValue=UserInfo().QueryTokenValidity(Token=ScanToken)
                if TokenQueryReturnValue:#如果Token存在
                    Uid=UserInfo().QueryUidWithToken(ScanToken)#如果登录成功后就来查询用户名
                    if Uid!=None:
                        UserOperationLogRecord(request, request_api="scan", uid=Uid)
                        Sid=ActiveScanList().Write(uid=Uid,url=ScanUrl,proxy=ScanProxy,status=0,module=ScanModule,threads=ScanThreads)#写入用户关系表,然后返回sid下发给任务
                        MedusaScan.delay(ScanUrl,ScanModule,ScanThreads,ScanAgentHeader,ScanProxy,Uid=Uid,Sid=Sid)#调用扫描处理函数
                        return JsonResponse({'message': '任务下发成功👌', 'code': 200, })
                    else:
                        return JsonResponse({'message': '诶诶诶诶？？？怎么会查不到用户名呢？？？？', 'code': 404, })
                else:
                    return JsonResponse({'message': '请登录获取令牌秘钥~', 'code': 404, })
            else:
                return JsonResponse({'message': '类型错误！', 'code': 500, })

        except Exception as e:
            ErrorLog().Write("Web_Api_VulnerabilityQuery_ActiveScanListQuery(def)", e)
            return JsonResponse({'message': '莎酱坏掉啦！', 'code': 500, })
    else:
        return JsonResponse({'message': '请使用Post请求', 'code': 500, })

